from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_moment import Moment
from flask_socketio import SocketIO
from consta import Config
from app import celeryapp
import json
from flask_wtf.csrf import CSRFProtect

bootstrap=Bootstrap()
db=SQLAlchemy()
moment=Moment()
socketio=SocketIO()
csrf=CSRFProtect()

login_manager=LoginManager()
login_manager.session_protection='strong'
login_manager.login_view='auth.login'

from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS

with open('private.json','r',encoding='utf8') as f:
    private=json.load(f)

# influxdb_client=InfluxDBClient(url="http://localhost:8086",token='O4lo6t8NbntoUqI5Shc9roF7KqdQztUQLFHQJCNHnBH6C7OkA8NT3VbvOr9-zNZXBqJv3UOzB0PQJ7Iw75wBLg==',org='tellw.org') # noteb wsl influxdb 秘钥 不要删 仅在此有备份

influxdb_client=InfluxDBClient(url=f'http://{private["influxdb_host"]}:8086',token=private['influxdb_token'],org=private['influxdb_org'])

buckets_api=influxdb_client.buckets_api()
buckets=buckets_api.find_buckets().buckets
bucket_names=[]
for bucket in buckets:
    bucket_names.append(bucket.name)
if 'btresults' not in bucket_names:
    buckets_api.create_bucket(bucket_name='btresults',org='tellw.org')
influxdb_write_api=influxdb_client.write_api(write_options=SYNCHRONOUS)
query_api=influxdb_client.query_api()
delete_api=influxdb_client.delete_api()

def create_app():
    app=Flask(__name__)
    app.config.from_object(Config)

    bootstrap.init_app(app)
    db.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    socketio.init_app(app,cors_allowed_origins='*')
    csrf.init_app(app)

    celery=celeryapp.create_celery_app(app)
    celeryapp.celery=celery

    from app.main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from app.auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint,url_prefix='/auth')

    from app.exec import exec as exec_blueprint
    app.register_blueprint(exec_blueprint,url_prefix='/exec')
    
    return app

# app,celery=create_app()